<template>
	<view class="container">
		<button @click="toggleMessage">私信接收</button>
		<view class="message" v-if="showMessages">
			<text>{{ post.title }}<br>{{ post.content }}</text>
			<view v-for="(message, index) in messages" :key="index">
				<text v-if="message.fromUser === post.userId">作者回复: {{ message.content }}</text>
				<text v-else>{{ getNickname(message.fromUser) }} 评论: {{ message.content }}</text>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				post: {},
				messages: [],
				showMessages: false,
				users: {}
			};
		},
		onLoad() {
			this.fetchPostsAndComments();
		},
		methods: {
			fetchPostsAndComments() {
				this.$request({
					url: '/message',
					method: 'GET',
				}).then(res => {
					// console.log('接收到的帖子和评论数据:', res);
					this.post = res.data.post;
					this.messages = res.data.messages;

					// 初始化 users 对象
					this.users = {};

					// 遍历 postList 获取用户 ID 并请求用户详情
					const userIds = [...new Set(this.messages.map(m => m.fromUser)), ...new Set(this.messages.map(
						m => m.toUser))];
					userIds.forEach(userId => {
						this.fetchUserProfile(userId);
					});
				}).catch(err => {
					console.error('获取帖子和评论失败:', err);
				});
			},
			fetchUserProfile(userId) {
				this.$request({
					url: '/users/profile',
					method: 'GET',
					header: {
						Authorization: uni.getStorageSync('token')
					}
				}).then(res => {
					if (res.code === 200) {
						this.users[userId] = res.data.username;
					} else {
						console.error(`获取用户 ID 为 ${userId} 的信息失败`);
					}
				}).catch(err => {
					console.error(`获取用户 ID 为 ${userId} 的信息失败`, err);
				});
			},
			getNickname(userId) {
				// console.log('Fetching nickname for userId:', userId); // 调试信息
				return this.users[userId] || '未知用户';
			},
			toggleMessage() {
				this.showMessages = !this.showMessages;
			}
		}
	};
</script>

<style>
	* {
		margin: 3px;
	}

	.view-container {
		text-align: center;
	}

	.message {
		color: #333;
		line-height: 1.5;
		padding: 10px;
		background-color: #FFFFF0;
		border: 1px solid #ddd;
		border-radius: 5px;
		box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
		margin-bottom: 30px;
	}

	text {
		font-size: 13px;
		font-weight: bold;
	}
</style>